<?php
/**
 * Created by PhpStorm.
 * User: huangpeng3
 * Date: 2018/1/5
 * Time: 下午1:45
 * 用户登录模型
 */
namespace Home\Model;

use Think\Model;

class LoginModel extends Model
{

    protected $tableName = 'coin_user_info';

    /**
     * @param $username
     * @param $password
     * 用户登录验证
     */
    public function checkuser($username, $password)
    {
        $rtn = array();
        $login_type = 'phone';
        if ($this->check_three($login_type, $username) < 3) {
            $map[$login_type] = $username;
            if ($res = $this->where($map)->select()) {
                if ($res[0]['password'] == md5($password . 'coinmd5')) {
                    $this->change_error_num($login_type, $username, 0);
                    unset($res[0]['password']);
                    $_SESSION['user_info'] = $res[0];
                    $rtn['status'] = true;
                    $rtn['info'] = '登录成功';
                    $rtn['flag'] = 0;
                } else {
                    $this->change_error_num($login_type, $username, 1);
                    $rtn['status'] = false;
                    $rtn['info'] = '密码错误';
                    $rtn['flag'] = -1;
                }
            } else {
                $rtn['status'] = false;
                $rtn['info'] = '用户名不存在';
                $rtn['flag'] = -2;
            }

        } else {
            $rtn['status'] = false;
            $rtn['info'] = '密码错误三次,请一段时间后再试';
            $rtn['flag'] = -3;
        }
        return $rtn;
    }


    /**
     * @param $login_type
     * @param $username
     * @param int $operation
     * 改变用户登录的错误次数
     */
    public function change_error_num($login_type, $username, $operation = 1)
    {
        $map[$login_type] = $username;
        $this->where($map)->setField('last_error_time', time());
        if ($operation) {
            //错误次数+1, 当前时间
            $this->where($map)->setInc('error_num', '1');
        } else {
            //错误次数清零
            $this->where($map)->setField('ip', get_client_ip());
            $this->where($map)->setField('error_num', 0);
        }

    }

    /**
     * @param $login_type
     * @param $username
     * @return int
     * 检测错误次数
     */
    public function check_three($login_type, $username)
    {
        $map = array();
        $map[$login_type] = $username;
        $rst = $this->where($map)->getField('error_num, last_error_time');
        $num = $rst['error_num'];
        $time = $rst['last_error_time'];
        if ($num == 3) {
            //是否超过一小时
            $time_delta = time() - $time;
            if ($time_delta > 3600) {
                $this->where($map)->setField('error_num', 0);
                return 0;
            } else {
                return $num;
            }
        } else {
            return $num;
        }
    }
}